use crate::http::server::error::{Error, HttpResponseError};
use crate::http::server::handler::watch::WsHandler;
use crate::mq;
use axum::extract::Path;
use axum::{
    extract::{
        ws::WebSocket, State,
        WebSocketUpgrade,
    },
    http::StatusCode,
};
use std::sync::Arc;
use wanmesh_common::{dto::ResponseCode, error::ResponseError};

pub struct NodeHandler {
    mq_client_factory: Arc<mq::client::Factory>,
}

impl NodeHandler {
    pub fn new(mq_client_factory: Arc<mq::client::Factory>) -> Self {
        NodeHandler {
            mq_client_factory,
        }
    }
    pub async fn watch(
        State(state): State<Arc<Self>>,
        Path(node_id): Path<String>,
        ws: WebSocketUpgrade,
    ) -> Result<axum::response::Response, Error> {
        if node_id == "" {
            return Err(Error::HttpResponseError(HttpResponseError {
                status_code: StatusCode::BAD_REQUEST,
                response: ResponseError {
                    code: ResponseCode(400),
                    message: "node_id没有设置".to_string(),
                    backtrace: Default::default(),
                },
            }));
        }

        let topic = mq::client::node::topic(node_id.as_str());
        let ws_handler = WsHandler::new(topic, state.mq_client_factory.clone());
        let ws_handle = async move |socket: WebSocket| {
            ws_handler.handle(socket).await;
        };

        Ok(ws.on_upgrade(ws_handle))
    }
}